package com.wy.filter;



import com.wy.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(value = "/contact/*",dispatcherTypes = {DispatcherType.FORWARD,DispatcherType.REQUEST})
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        // 判断用户登录成功的状态
        HttpSession session = request.getSession();
        // 获取登录成功的用户信息
        User user = (User) session.getAttribute("user");
        if(user==null){
            // 没有用户登录
            //获取本次请求的路径
            String uri = request.getRequestURI();
            System.out.println("本次请求的路径是:"+uri);
            String method = req.getParameter("method");
            session.setAttribute("oldUrl",uri+"?method="+method);

//            if(!"/contact/list.jsp".equals(uri)){
//                //将上次请求的资源路径存放到session中
//                session.setAttribute("oldUrl",uri);
//            }

            // 请求转发
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            // 重定向
            //response.sendRedirect("/login.jsp");
            return;
        }

        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
